<template>
    <div class="user-manage">
        <div class="user-header">
            <div class="search-box"> <!-- 搜索筛选表单区域 -->
                <!-- 创建水平布局的表单 -->
                <el-form :inline="true" class="form-inline" :model="formInline">
                    <!-- 用户名输入表单项 -->
                    <el-form-item label="用户名:">
                        <el-input v-model="formInline.loginAccount" placeholder="请输入用户名" class="input-width"></el-input>
                    </el-form-item>
                    <!-- 组织名称下框表单项 -->
                    <el-form-item label="组织名称:">
                        <el-select v-model="formInline.organization" placeholder="请选择组织名称" class="input-width"
                            clearable>
                            <el-option label="锐擎体育" value="锐擎体育"></el-option>
                            <el-option label="韶关学院" value="韶关学院"></el-option>
                        </el-select>
                    </el-form-item>
                    <!-- 手机输入表单项 -->
                    <el-form-item label="手机:">
                        <el-input v-model="formInline.phone" placeholder="请输入手机" class="input-width"></el-input>
                    </el-form-item>
                    <!-- 类型下拉框表单项 -->
                    <el-form-item label="类型:">
                        <el-select v-model="formInline.type" placeholder="请选择类型" class="input-width" clearable>
                            <el-option label="外部" value="外部"></el-option>
                            <el-option label="企业" value="企业"></el-option>
                        </el-select>
                    </el-form-item>

                    <!-- 搜索按钮表单项 -->
                    <el-form-item>
                        <el-button type="primary" @click="handleSearch">搜索</el-button>
                    </el-form-item>
                </el-form>
            </div>
            <div class="function-box">
                <el-button type="primary" class="email-add">邮箱邀请</el-button>
                <el-button type="primary" class="user-add" @click="handleEditOrAdd('add', null)">新增</el-button>
            </div>
        </div>

        <div class="table">
            <el-table :data="tableData" style="width: 100%" v-if="tableData.length > 0">
                <el-table-column v-for="item in tableLabel" :key="item.prop" :width="item.width ? item.width : 125"
                    :prop="item.prop" :label="item.label" />
                <el-table-column label="Operations" width="350">
                    <template #="scope">
                        <div class="operations-box">
                            <!-- 编辑链接 -->
                            <span class="operation-link" @click="handleEditOrAdd('edit', scope.row)">编辑</span>
                            <!-- 展开/收起链接 -->
                            <span class="operation-link" @click="handleToggleMore(scope.$index)">
                                {{ expandedRowIndex === scope.$index ? '收起' : '更多' }}
                            </span>
                            <!-- 展开状态下的操作链接 -->
                            <template v-if="expandedRowIndex === scope.$index">
                                <span class="operation-link danger">禁用</span>
                                <span class="operation-link danger" @click="handleDelete(scope.row)">删除</span>
                                <span class="operation-link danger">重置密码</span>
                            </template>
                            <span class="operation-link unlock" @click="handleUnlock(scope.row)">解锁</span>
                        </div>
                    </template>
                </el-table-column>
            </el-table>
            <div v-else class="empty-state">暂无数据</div>
        </div>

        <!-- 编辑/新增用户对话框 -->
        <el-dialog v-model="dialogVisible" :title="action === 'add' ? '新增用户' : '编辑用户'" width="35%"
            :before-close="handleClose">
            <el-form :inline="true" :model="formUser" :rules="rules" ref="userForm">
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="用户名" prop="loginAccount">
                            <el-input v-model="formUser.loginAccount" placeholder="请输入用户名" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="姓名" prop="nickname">
                            <el-input v-model="formUser.nickname" placeholder="请输入姓名" />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row>
                    <el-col :span="12">
                        <el-form-item label="手机号" prop="phone">
                            <el-input v-model="formUser.phone" placeholder="请输入手机号" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="邮箱" prop="email">
                            <el-input v-model="formUser.email" placeholder="请输入邮箱" />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row>
                    <el-col :span="12">
                        <el-form-item class="select-learn" label="组织/岗位" prop="organization">
                            <el-select v-model="formUser.organization" placeholder="请选择组织/岗位" class="full-width-select">
                                <el-option label="技术部" value="技术部" />
                                <el-option label="市场部" value="市场部" />
                                <el-option label="韶关学院" value="韶关学院" />
                                <el-option label="锐擎体育" value="锐擎体育" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item class="select-learn" label="类型" prop="type">
                            <el-select v-model="formUser.type" placeholder="请选择类型" class="full-width-select">
                                <el-option label="企业" value="企业" />
                                <el-option label="外部" value="外部" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row>
                    <el-col :span="12">
                        <el-form-item class="select-learn" label="状态" prop="status">
                            <el-select v-model="formUser.status" placeholder="请选择状态" class="full-width-select">
                                <el-option label="正常" value="active" />
                                <el-option label="禁用" value="inactive" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="创建时间" prop="createTime" v-if="action === 'edit'">
                            <el-date-picker v-model="formUser.createTime" type="datetime" placeholder="请选择日期"
                                style="width: 100%;" disabled />
                        </el-form-item>
                        <!-- 隐藏的ID字段 -->
                        <el-form-item prop="id" v-show="false">
                            <el-input v-model="formUser.id" />
                        </el-form-item>
                    </el-col>
                </el-row>

                <!-- 操作按钮 -->
                <el-row style="justify-content: flex-end; margin-top: 20px;">
                    <el-form-item>
                        <el-button @click="handleCancel">取消</el-button>
                        <el-button type="primary" @click="onSubmit">确定</el-button>
                    </el-form-item>
                </el-row>
            </el-form>
        </el-dialog>
    </div>
</template>

<script lang="ts" setup>
import { reactive, getCurrentInstance, onMounted, type ComponentPublicInstance, ref } from 'vue';
import { ElMessageBox, type FormInstance, type FormItemRule } from 'element-plus'
import 'element-plus/dist/index.css'

// 定义用户数据接口
interface UserData {
    id?: string;
    loginAccount: string;
    nickname: string;
    organization: string;
    phone: string;
    email: string;
    createTime: string;
    type: string;
    status: string;
}

const formInline = reactive({
    loginAccount: '',
    organization: '',
    phone: '',
    type: ''
});

const searchConfig = reactive({
    id: '',
    loginAccount: '',
    organization: '',
    phone: '',
    type: ''
})

const tableData = ref<UserData[]>([])

// 修复类型问题，处理getCurrentInstance可能返回null的情况
const instance = getCurrentInstance()
const proxy = instance?.proxy as ComponentPublicInstance & { $api: any } | null

// 获取用户数据的函数
const getUserData = async () => {
    try {
        if (proxy) {
            // console.log("searchConfig是：" + JSON.stringify(searchConfig))
            // 调用API获取用户数据，将searchConfig作为查询参数传递
            const res = await proxy.$api.getUserData(searchConfig)

            if (res && res.list) {
                // console.log("接口调用结束")
                tableData.value = res.list.map((item: UserData) => {
                    return {
                        id: item.id,
                        loginAccount: item.loginAccount,
                        nickname: item.nickname,
                        organization: item.organization,
                        phone: item.phone,
                        email: item.email,
                        createTime: item.createTime,
                        type: item.type,
                        status: item.status
                    }
                })
            }
        }
    } catch (error) {
        console.error('获取用户数据失败:', error)
    }
}

const tableLabel = reactive([
    {
        label: '用户名',
        prop: 'loginAccount',
        width: '180',
    },
    {
        label: '姓名',
        prop: 'nickname',
    },
    {
        label: '手机号',
        prop: 'phone',
        width: '150',
    },
    {
        label: '邮箱',
        prop: 'email',
        width: '230',
    },
    {
        label: '组织/岗位',
        prop: 'organization',
        width: '180',
    },
    {
        label: '创建时间',
        prop: 'createTime',
        width: '200',
    },
    {
        label: '类型',
        prop: 'type',
        width: '120',
    },
    {
        label: '状态',
        prop: 'status',
        width: '100',

    }
])

const handleSearch = () => {
    // 将所有表单字段赋值给搜索配置
    Object.assign(searchConfig, {
        loginAccount: formInline.loginAccount,
        organization: formInline.organization,
        phone: formInline.phone,
        type: formInline.type
    })
    getUserData()
}

const handleDelete = (val: UserData) => {
    ElMessageBox.confirm("是否删除该用户？", "提示", {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true,
    }).then(async () => {
        // console.log("删除用户id是：" + JSON.stringify(val))
        if (!val.id) {
            ElMessage({
                type: 'error',
                message: '用户ID不存在，无法删除'
            })
            return
        }
        await proxy?.$api.deleteUser({ id: val.id }).then(() => {
            ElMessage({
                showClose: true,
                message: '删除成功',
                type: 'success'
            })
            getUserData()
        }).catch(() => {
            ElMessage({
                type: 'info',
                message: '已取消删除'
            })
        })
    })
}

onMounted(() => {
    getUserData()
})

const handleToggleMore = (index: number) => {
    // 切换展开状态
    if (expandedRowIndex.value === index) {
        expandedRowIndex.value = -1 // 如果再次点击同一行，则收起
    } else {
        expandedRowIndex.value = index // 展开当前行
    }
}

const handleEditOrAdd = (type: string, row: UserData | null) => {
    action.value = type
    dialogVisible.value = true
    // 如果是编辑操作，使用被编辑的那一行的数据填充表单数据
    if (type === 'edit' && row) {
        // 填充示例数据
        Object.keys(formUser).forEach(key => {
            (formUser as any)[key] = (row as any)[key] || ''
        })
    } else {
        // 新增操作，清空表单
        Object.keys(formUser).forEach(key => {
            (formUser as any)[key] = ''
        })
        // 清除表单验证错误
        if (userForm.value) {
            userForm.value.clearValidate()
        }
    }
}

// 处理解锁按钮事件
const handleUnlock = (row: any) => {
    console.log('点击解锁按钮，当前行数据：', row)
}

// 添加展开行索引的响应式变量
const expandedRowIndex = ref(-1)

// 添加对话框相关变量和方法
const dialogVisible = ref(false)
const action = ref('')
const formUser = reactive({
    id: '',
    loginAccount: '',
    nickname: '',
    phone: '',
    email: '',
    organization: '',
    type: '',
    status: '',
    createTime: ''
})

const userForm = ref<FormInstance>()

// 表单验证规则
const rules = reactive<{
  [key: string]: FormItemRule[]
}>({
    loginAccount: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' }
    ],
    nickname: [
        { required: true, message: '请输入姓名', trigger: 'blur' }
    ],
    phone: [
        { required: true, message: '请输入手机号', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
    ],
    email: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        { type: 'email' as const, message: '邮箱格式不正确', trigger: 'blur' }
    ],
    organization: [
        { required: true, message: '请选择组织/岗位', trigger: 'change' }
    ],
    type: [
        { required: true, message: '请选择用户类型', trigger: 'change' }
    ],
    status: [
        { required: true, message: '请选择状态', trigger: 'change' }
    ]
})

const handleClose = () => {
    dialogVisible.value = false
    // 关闭对话框时清除表单验证状态
    if (userForm.value) {
        userForm.value.clearValidate()
    }
}

const handleCancel = () => {
    dialogVisible.value = false
    // 取消时也清除表单验证状态
    if (userForm.value) {
        userForm.value.clearValidate()
    }
}

const onSubmit = () => {
    // 表单提交逻辑
    if (!userForm.value) return
    userForm.value.validate((valid: boolean) => {
        if (valid) {
            // 验证通过，执行提交逻辑
            console.log('表单验证通过，提交数据:', formUser)
            let res = null;
            if (action.value === 'add') {
                res = proxy?.$api.addUser(formUser)
            } else {
                res = proxy?.$api.updateUser(formUser)
            }
            
            // 处理响应结果
            if (res) {
                res.then(() => {
                    ElMessage({
                        showClose: true,
                        message: action.value === 'add' ? '新增用户成功' : '更新用户成功',
                        type: 'success'
                    })
                    dialogVisible.value = false
                    getUserData() // 刷新用户列表
                }).catch((error: any) => {
                    console.error('操作失败:', error)
                    ElMessage({
                        showClose: true,
                        message: action.value === 'add' ? '新增用户失败' : '更新用户失败',
                        type: 'error'
                    })
                })
            }
        } else {
            console.log('表单验证失败')
            // 不返回任何值，只记录日志
        }
    })
}
</script>

<style scoped lang="less">
.user-manage {
    width: 100%;
    padding: 20px;
    box-sizing: border-box;
}

.user-header {
    display: flex;
    justify-content: space-between;
    margin-bottom: 20px;
    width: 100%;

    .search-box {
        flex: 1;
    }

    .function-box {
        padding-top: 0px;
        white-space: nowrap;
    }
}

.form-inline {
    display: flex;
    flex-wrap: wrap;
    align-items: center;

    :deep(.el-form-item) {
        margin-right: 20px;
        margin-bottom: 0;
    }
}

.input-width {
    width: 200px;
}

.table {
    width: 100%;

    .operations-box {
        display: flex;
        flex-wrap: wrap;
        gap: 10px;
        align-items: center;

        .operation-link {
            color: #409eff;
            cursor: pointer;
            font-size: 12px;
            padding: 2px 4px;
            border-radius: 2px;
            transition: all 0.3s;

            &:hover {
                color: #66b1ff;
                background-color: #ecf5ff;
                text-decoration: underline;
            }

            &.danger {
                color: #f56c6c;

                &:hover {
                    color: #f78989;
                    background-color: #fef0f0;
                }
            }

            &.unlock {
                color: #e6a23c;

                &:hover {
                    color: #ebb563;
                    background-color: #fdf6ec;
                }
            }
        }
    }
}

.empty-state {
    text-align: center;
    padding: 40px 0;
    color: #999;
}

.full-width-select {
    width: 100%;
}
</style>